package com.xh.bussiness.jingyou.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.*;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Utility {

	/*
	 * 获取当前用户请求头
	 */
	private static String getTag(URLConnection connection) throws JSONException {
		JSONObject jo = new JSONObject();

		Map<String, List<String>> map = connection.getRequestProperties();

		for (String key : map.keySet()) {
			if (key != null && key.length() > 0) {
				jo.put(key, map.get(key));
			}
		}

		// 当前用户IP
		jo.put("IP", getUserIP());

		return jo.toString();
	}

	/*
	 * 获取当前用户IP
	 */
	private static String getUserIP() {
		// 请修改为当前用户IP
		return "";
	}

	/*
	 * 密码强度检查
	 */
	public static Boolean isWeak(String password) {
		password = password.toLowerCase();

		if (password == null || password.length() < 6 || password.replace(password.charAt(0), ' ').trim() == "")
			return true;

		String[] m_simples = new String[] { "1234567890", "0987654321", "123123", "123321", "321321", "147258369",
				"147369", "abcdefgh", "qwertyuiop", "asdfghjkl", "zxcvbnm" };

		for (String ia : m_simples) {
			if (ia == password)
				return true;
		}

		return false;
	}

	/*
	 * JSON转对象
	 */
	public static <T> T convertTo(String json, Type typeOfT) throws Exception {
		Gson gson = new Gson();

		return gson.fromJson(json, typeOfT);
	}

	/*
	 * JSON转对象
	 */
	public static <T> T convertTo(String json, Class<T> classOfT) throws Exception {
		Gson gson = new Gson();

		return gson.fromJson(json, classOfT);
	}

	/*
	 * 向服务器发送请求
	 */
	private static String send(String token, String method, String url, String param) {
		DataOutputStream out = null;
		BufferedReader in = null;
		String result = "";

		try {
			URL realUrl = new URL(url);

			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();

			connection.setRequestMethod(method);
			connection.setRequestProperty("accept", "application/json; charset=UTF-8");
			connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
			connection.setRequestProperty("user-agent", "Mozilla/5.0");

			if (token != null && token.length() > 0) {
				connection.setRequestProperty("authorization", "Token " + token);
			}

			connection.setRequestProperty("tag", getTag(connection));

			if (method == "POST" || method == "PUT") {
				connection.setDoOutput(true);
				connection.setDoInput(true);

				byte[] bs = param.getBytes("UTF-8");

				connection.connect();
				out = new DataOutputStream(connection.getOutputStream());
				out.write(bs);
				out.flush();
			}

			int code = connection.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK) {
				in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF8"));
			} else {
				in = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF8"));
			}

			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

			if (code != HttpURLConnection.HTTP_OK) {
				throw new Exception(result);
			}
			//关闭IO和连接
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/*
	 * 表单上传
	 */
	public static String sendForm(String token, String url, Map<String, String> fields, Map<String, String> files) {
		DataOutputStream out = null;
		BufferedReader in = null;
		StringBuffer sb = null;
		String result = "";

		String BOUNDARY = "----123852369147ABC";

		try {
			URL realUrl = new URL(url);

			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();

			if (token != null && token.length() > 0) {
				connection.setRequestProperty("authorization", "Token " + token);
			}

			connection.setRequestProperty("tag", getTag(connection));

			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("User-Agent", "Mozilla/5.0");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

			out = new DataOutputStream(connection.getOutputStream());

			if (fields != null) {
				Iterator<Map.Entry<String, String>> iter = fields.entrySet().iterator();

				sb = new StringBuffer();
				while (iter.hasNext()) {
					Map.Entry<String, String> entry = iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					sb.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					sb.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
					sb.append(inputValue);
				}
				out.write(sb.toString().getBytes("UTF-8"));
			}

			if (files != null) {
				Iterator<Map.Entry<String, String>> iter = files.entrySet().iterator();

				while (iter.hasNext()) {
					Map.Entry<String, String> entry = iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					File file = new File(inputValue);
					String fileName = file.getName();

					String contentType = GetContentType(fileName);

					sb = new StringBuffer();
					sb.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					sb.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + fileName
							+ "\"\r\n");
					sb.append("Content-Type:" + contentType + "\r\n\r\n");

					out.write(sb.toString().getBytes("UTF-8"));

					DataInputStream dsFile = new DataInputStream(new FileInputStream(file));
					byte[] bytes = new byte[1024];
					int count = 0;
					while ((count = dsFile.read(bytes)) != -1) {
						out.write(bytes, 0, count);
					}
					dsFile.close();
				}
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
			out.write(endData);
			out.flush();
			out.close();

			int code = connection.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK) {
				in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF8"));
			} else {
				in = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF8"));
			}

			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

			if (code != HttpURLConnection.HTTP_OK) {
				throw new Exception(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	/*
	 * 表单上传
	 */
	public static <T> T sendForm(String token, String url, Map<String, String> fields, Map<String, String> files, Type typeOfT) throws Exception {
		String json = Utility.sendForm(token, url, fields, files);

		return Utility.convertTo(json, typeOfT);
	}

	/*
	 * 获取文件的ContentType
	 */
	private static String GetContentType(String file) {
		try {
			Path path = Paths.get(file);

			return Files.probeContentType(path);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	/*
	 * 发送GET请求
	 */
	public static String sendGet(String token, String url) throws Exception {
		return Utility.send(token, "GET", url, "");
	}

	/*
	 * 发送GET请求
	 */
	public static <T> T sendGet(String token, String url, Type typeOfT) throws Exception {
		String json = Utility.sendGet(token, url);

		return Utility.convertTo(json, typeOfT);
	}

	/*
	 * 发送GET请求
	 */
	public static <T> T sendGet(String token, String url, Class<T> classOfT) throws Exception {
		String json = Utility.sendGet(token, url);

		return Utility.convertTo(json, classOfT);
	}

	/*
	 * 发送POST请求
	 */
	public static String sendPost(String token, String url, String param) {
		return Utility.send(token, "POST", url, param);
	}
	
	/*
	 * 发送POST请求
	 */
	public static <T> T sendPost(String token, String url, Type typeOfT) throws Exception {
		String json = Utility.sendPost(token, url, "");

		return Utility.convertTo(json, typeOfT);
	}

	/*
	 * 发送POST请求
	 */
	public static <T> T sendPost(String token, String url, Class<T> classOfT) throws Exception {
		String json = Utility.sendPost(token, url, "");

		return Utility.convertTo(json, classOfT);
	}

	/*
	 * 发送POST请求
	 */
	public static <T, O> T sendPost(String token, String url, O o, Type typeOfT) throws Exception {
		Gson gson = new Gson();

		// System.out.println(gson.toJson(o));

		String json = Utility.sendPost(token, url, gson.toJson(o));

		// System.out.println(json);

		return Utility.convertTo(json, typeOfT);
	}

	/*
	 * 发送POST请求
	 */
	public static <T, O> T sendPost(String token, String url, O o, Class<T> classOfT) throws Exception {
		Gson gson = new Gson();

		String json = Utility.sendPost(token, url, gson.toJson(o));

		return Utility.convertTo(json, classOfT);
	}

	/*
	 * 发送PUT请求
	 */
	public static byte[] sendPut(String token, String url) throws Exception {
		String json = Utility.send(token, "PUT", url, "");

		Gson gson = new Gson();

		return gson.fromJson(json, new TypeToken<byte[]>() {
		}.getType());
	}

	/*
	 * 发送DELETE请求
	 */
	public static <T> T sendDelete(String token, String url, Type typeOfT) throws Exception {
		String json = Utility.send(token, "DELETE", url, "");

		return Utility.convertTo(json, typeOfT);
	}

	/*
	 * 写DOC文件
	 */
	public static void WriteDoc(String name, byte[] data) throws Exception {
		File file = new File(name);

		FileOutputStream out = new FileOutputStream(file);

		out.write(data, 0, data.length);

		out.close();
	}
}